# -*- coding: utf-8 -*-
import os
import time
import configparser
from pathlib import Path
from datetime import datetime, timedelta
import logging
import argparse

class LogCleaner:
    def __init__(self, config_path=None):
        config_file = config_path or Path(__file__).parent / 'log_cleaner_config.ini'
        self.config = self._load_config(config_file)
        self.logger = self._setup_logger()
        self.retention_date = datetime.now() - timedelta(
            days=self.config.getint('Settings', 'keep_days')
        ) if self.config.getint('Settings', 'keep_days') > 0 else None

    def _load_config(self, config_file):
        config = configparser.ConfigParser()
        try:
            # 先尝试UTF-8编码
            with open(config_file, 'r', encoding='utf-8') as f:
                config.read_file(f)
        except UnicodeDecodeError:
            # 如果失败尝试GBK编码
            try:
                with open(config_file, 'r', encoding='gbk') as f:
                    config.read_file(f)
            except Exception as e:
                raise ValueError(f"无法解析配置文件编码: {str(e)}")
        except Exception as e:
            raise FileNotFoundError(f"配置文件加载失败: {str(e)}")
        return config

    def _setup_logger(self):
        logging.basicConfig(
            filename='log_cleaner.log',
            format='%(asctime)s - %(levelname)s - %(message)s',
            level=logging.INFO
        )
        return logging.getLogger()

    def _is_old_file(self, file_path):
        if not self.retention_date:
            return True
        mtime = datetime.fromtimestamp(os.path.getmtime(file_path))
        return mtime < self.retention_date

    def _should_delete(self, file_name):
        ext = Path(file_name).suffix.lower()
        exts = self.config['Settings']['file_extensions'].split(',')
        keywords = self.config['Settings']['file_keywords'].split(',')
        
        return (ext in exts) or any(kw in file_name for kw in keywords)

    def _file_generator(self):
        target_dir = os.path.normpath(self.config['Settings']['target_directory'])
        batch_size = self.config.getint('Settings', 'batch_size')
        current_batch = []

        for entry in os.scandir(target_dir):
            if entry.is_file() and self._should_delete(entry.name):
                if self._is_old_file(entry.path):
                    current_batch.append(entry.path)
                    if len(current_batch) >= batch_size:
                        yield current_batch
                        current_batch = []
        if current_batch:
            yield current_batch

    def clean(self):
        total_deleted = 0
        start_time = time.time()
        self.logger.info("Starting log cleanup process...")

        try:
            for batch in self._file_generator():
                for file_path in batch:
                    try:
                        os.remove(file_path)
                        total_deleted += 1
                        self.logger.info(f"Deleted: {file_path}")
                    except Exception as e:
                        self.logger.error(f"Error deleting {file_path}: {str(e)}")
                
                # 显示进度但不占用太多内存
                print(f"\rProcessed {total_deleted} files...", end='', flush=True)
                
            print(f"\nCleanup completed. Total deleted: {total_deleted}")
            print(f"总耗时: {time.time() - start_time:.2f} 秒")
            self.logger.info(f"Cleanup completed. Total deleted: {total_deleted}")

        except KeyboardInterrupt:
            print("\nOperation cancelled by user.")
            print(f"已运行时间: {time.time() - start_time:.2f} 秒")
            self.logger.warning("Cleanup process interrupted by user")

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--config', help='指定配置文件路径')
    args = parser.parse_args()
    cleaner = LogCleaner(args.config)
    cleaner.clean() 